package ooday04;
/* 多态演示 */
public class PolymorphicDemo {
    public static void main(String[] args) {
        //演示向上造型的语法：

        //狗是狗，能引用出父类中和子类中的所有属性
        Dog o1 = new Dog("小黑",3,"黑色");
        //狗是动物，能引用出父类中的所有属性，不能引用出子类中的属性
        //向上造型
        Anmial o2 = new Dog("小白",4,"白色");
        //狗会游泳，只能引用出接口中的方法
        //向上造型
        Swim o3 = new Dog("小绿",5,"绿色");



        //演示向上造型的第一点应用
        //创建一个Master对象
        Master master = new Master();
        //创建三个对象,并赋值
        Dog dog = new Dog("小黑",3,"黑");
        Chick chick = new Chick("小紫",5,"紫");
        Fish fish = new Fish("小橙",4,"橙");
        //调用子类中的feed方法，赋值传参，传参的同时，系统自动做了向上造型
        master.feed(dog);
        master.feed(chick);
        master.feed(fish);

        System.out.println("===================================================");

        //演示向上造型的第二点应用
        Anmial[] anmia = new Anmial[5];
        //创建五个对象，并赋值
        anmia[0] = new Dog("小黑",3,"黑");
        anmia[1] = new Chick("小紫",5,"紫");
        anmia[2] = new Fish("小橙",4,"橙");
        anmia[3] = new Dog("小黑",3,"黑");
        anmia[4] = new Chick("小紫",5,"紫");
        for (int i = 0; i < anmia.length; i++) {
            //输出每个动物的名字     父类类型
            System.out.println(anmia[i].name);
            //让每一个动物吃饭，调用子类中的eat方法
            anmia[i].eat();
            //让每一个动物喝水,调用父类中的drink方法
            anmia[i].drink();

            //判断anmia[i]是否是狗的子类
            if (anmia[i] instanceof Dog){
                //强转anmia[i]为Dog类型，并赋值给dog1
                Dog dog1 = (Dog)anmia[i];
                //调用Dog中的lookHome方法
                dog1.lookHome();
            }
            //判断anmia[i]是否是鸡的子类
            if (anmia[i] instanceof Chick){
                //强转anmia[i]为Chick类型，并赋值给c
                Chick c = (Chick)anmia[i];
                //调用Chick中的layEgg方法
                c.layEgg();
            }
            //适用于所有实现了Swim接口的类
            if (anmia[i] instanceof Swim){
                //强转anmia[i]为Swim类型，并赋值给s
                Swim s = (Swim) anmia[i];
                //调用Swim中的swim方法
                s.swim();
            }

        }

        //演示强转成功的条件
        //创建对象
        Anmial o = new Dog("小黑",3,"黑");
        //引用o所指向的对象，是Dog类型
        Dog g = (Dog)o;
        //引用o所指向的对象，实现Swim接口
        Swim s = (Swim)o;
        //运行时会发生ClassCastException类型转换异常
        //Fish f = (Fish)o;

        System.out.println(o instanceof Dog);//true
        System.out.println(o instanceof Swim);//true
        System.out.println(o instanceof Fish);//false
        //判断o是否是Fish类型
        if (o instanceof Fish){
            Fish d = (Fish) o;
        }

    }
}
